/**
 * 郭楠project
 * com.gn.micblog.util
 * CommonUtils.java
 * 创建人:TonyGuo 
 * 时间：2016年11月28日-上午12:13:27 
 * 2016Tm公司-版权所有
 */
package com.gn.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * CommonUtils
 * 创建人:TonyGuo
 * 时间：2016年11月28日-上午12:13:27 
 * @version 1.0.0
 * 
 */
public class CommonUtils {
	/**百度调用接口私钥-apikey*/
	private static final String BAIDU_APIKEY="08ec4c6876b14da737bc67fd1e5114cb";
	
	
	/**
	 * 编码
	 * @throws UnsupportedEncodingException 
	 * */
	public static String Iso2UTF8(String str) throws UnsupportedEncodingException{
		String s=new String(str.getBytes("iso-8859-1"), "utf-8");
		return s;
	}
	
	/**
	 * String to Date
	 * */
	public static Date str2Date(String date){
		SimpleDateFormat sdf=null;
		Date d=null;
		if(!"".equals(date)){
			sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				d=sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return d;
	}
	
	/**
	 * Date to String
	 * */
	public static String date2Str(Date d){
		SimpleDateFormat sdf=null;
		String str="";
		if(d!=null){
			sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			str=sdf.format(d);
			return str;
		}
		return "";
	}
	
	/**
	 * 根据ip获取地理位置接口调用
	 * */
	public static String getPositionById(String ip){
		String httpUrl = "http://apis.baidu.com/apistore/iplookupservice/iplookup";
		String httpArg = "ip="+ip;
		String jsonResult = request(httpUrl, httpArg);
		JSONObject json=JSONObject.fromObject(jsonResult);
		System.out.println("json="+json);
		JSONObject rstData=JSONObject.fromObject(json.getString("retData"));
		
		String errMsg = json.getString("errMsg");//省份
		if(!"success".equals(errMsg)){
			return "ip_error";
		}
		String country = rstData.getString("country");//省份
		String province = rstData.getString("province");//省份
		String city = rstData.getString("city");//城市
		String district = rstData.getString("district");//地区
		String carrier = rstData.getString("carrier");//通讯运营商
		
		StringBuilder sb=new StringBuilder(country);
		sb.append(" "+province);
		sb.append(" "+city);
		sb.append(" "+district);
		sb.append(" ("+carrier+")");
		
		System.out.println("=====>>>"+sb.toString());
		return sb.toString();
	}
	
	/**
	 * @param urlAll :请求接口
	 * @param httpArg :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  BAIDU_APIKEY);
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	//获得客户端真实IP地址的方法：
	public static String getIpAddress(HttpServletRequest request) { 
	    String ip = request.getHeader("x-forwarded-for"); 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_CLIENT_IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	  } 
	
	//获得客户端真实IP地址的方法一：
	public static String getIPAddr1(HttpServletRequest request) {  
	    if (request.getHeader("x-forwarded-for") == null) {  
	        return request.getRemoteAddr();  
	    }  
	    return request.getHeader("x-forwarded-for");  
	}  
	//获得客户端真实IP地址的方法二：
	public static String getIpAddr2(HttpServletRequest request) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}
	

}
